package com.offics.loan.infrastructure.service;

import com.offics.loan.infrastructure.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.UUID;

/**
 * 文件存储服务
 */
@Service
@RequiredArgsConstructor
public class FileStorageService {

    @Value("${file.upload-dir:uploads}")
    private String uploadDir;

    @Value("${file.access-path:files}")
    private String accessPath;

    @Value("${file.server-url:http://localhost:8080}")
    private String serverUrl;

    /**
     * 存储文件
     *
     * @param file 文件
     * @param subDir 子目录
     * @return 文件访问URL
     */
    public String storeFile(MultipartFile file, String subDir) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new BusinessException("文件不能为空");
        }

        try {
            // 获取文件名
            String originalFilename = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));

            // 检查文件名是否包含无效字符
            if (originalFilename.contains("..")) {
                throw new BusinessException("文件名包含无效字符: " + originalFilename);
            }

            // 生成新的文件名
            String fileExtension = getFileExtension(originalFilename);
            String newFilename = UUID.randomUUID() + fileExtension;

            // 创建目标目录
            String targetDir = uploadDir;
            if (subDir != null && !subDir.isEmpty()) {
                targetDir = uploadDir + "/" + subDir;
            }

            Path targetLocation = Paths.get(targetDir).toAbsolutePath().normalize();
            Files.createDirectories(targetLocation);

            // 保存文件
            Path filePath = targetLocation.resolve(newFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 返回文件访问URL
            String fileUrl = serverUrl + "/" + accessPath;
            if (subDir != null && !subDir.isEmpty()) {
                fileUrl += "/" + subDir;
            }
            fileUrl += "/" + newFilename;

            return fileUrl;
        } catch (IOException ex) {
            throw new BusinessException("文件存储失败: " + ex.getMessage());
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param filename 文件名
     * @return 文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename.lastIndexOf(".") != -1) {
            return filename.substring(filename.lastIndexOf("."));
        }
        return "";
    }
}
